package concurrency;

import java.util.Random;
import java.util.concurrent.TimeUnit;

class Chef implements Runnable {
    private static int sCounter = 0;

    private final int mId = sCounter++;

    private final Restaurant mRestaurant;

    private static Random sRand = new Random(47);

    public Chef(Restaurant rest) {
        mRestaurant = rest;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                // Blocks until an order appears
                Order order = mRestaurant.mOrders.take();
                Food requestedItem = order.item();
                // Time to prepare order:
                TimeUnit.MILLISECONDS.sleep(sRand.nextInt(500));
                Plate plate = new Plate(order, requestedItem);
                WaitPerson waitPerson = order.getWaitPerson();
                waitPerson.mFilledOrders.put(plate);
            }
        } catch (InterruptedException e) {
            System.out.println(this + " interrupted");
            // e.printStackTrace();
        }
        // 下班，不在值班
        System.out.println(this + " off duty");
    }

    @Override
    public String toString() {
        return "Chef " + mId + " ";
    }
}
